<?php
class Table
{
    public static function query($sql)
    {
        $strDbUser = 'root'; $strDbPass = 'Wc20200521##';
        $strDbHost = '39.105.57.133:3306'; $strDbName = 'mc_vqz';
        $strDsn = "mysql:host=$strDbHost;dbname=$strDbName;";
        $strCharset = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'set names uft-8');
        return new PDO($strDsn, $strDbUser, $strDbPass, $strCharset);
    }

    /**
     * 测试查询
     * @param $table指定的数据表，$conditions查询条件，$orderBy排序条件
     */
    public static function setQquery($table,$conditions,$orderBy)
    {
        $sql = 'select * from '.$table;
        if ($conditions) { //条件
            $sql .= ' where ';
            foreach ($conditions as $k => $v) {
                $sql .= $k ? ' and ' : '';
                $sql .= $v[0].' '.$v[1].' \''.$v[2].'\'';
            }
        }
        if ($orderBy){ //排序
            $sql .= ' '.$orderBy[0].' order by '.$orderBy[1];
        }
        try {
            $query = self::query($sql);
            if (!$query) { return ''; }
            if (!$query->rowCount()) { return ''; }
            $list = $query->fetchAll(PDO::FETCH_ASSOC);
            if (!$list) { return ''; }
            return $list;
        } catch (PDOException $e) {
            return '';
        }
    }

    /**
     * 测试新增一条
     * @param $table指定的数据表，$adds新增的数组
     */
    public static function setInsert($table,$adds)
    {
        if (!$adds) {
            return array('code' => -3, 'msg' => "条件数据为空");
        }
        $sql = 'insert into '.$table.' (';
        foreach ($adds as $k => $v) {
            $sql .= $k ? ',' : ''; $sql .= $v[0];
        }
        $sql .= ') values (';
        foreach ($adds as $k => $v) {
            $sql .= $k ? ',' : ''; $sql .= '\''.$v[1].'\'';
        }
        $sql .= ')';
        try {
            $objDB = $this->getDBObj();
            $query = $objDB->exec($sql);
            if (!$query) {
                return array('code' => -2, 'msg' => "数据库操作失败");
            }
            return array('code' => 0, 'msg' => '数据库操作成功', 'data' => $query);
        } catch (PDOException $e) {
            return array('code' => -1, 'msg' => "数据库连接失败".$e->getMessage());
        }
    }
}